package team.nine.kuaichezuche.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import team.nine.kuaichezuche.model.VehicleInfo;
import team.nine.kuaichezuche.model.VehicleInstance;
import team.nine.kuaichezuche.model.User;
import team.nine.kuaichezuche.service.VehicleInstanceService;
import team.nine.kuaichezuche.service.UserService;

import java.util.*;

/**
 * 用户车辆控制器，处理用户相关的车辆信息请求
 */
@RestController
@RequestMapping("/api/user/vehicles")
public class UserVehicleController {

    @Autowired
    private VehicleInstanceService vehicleInstanceService;


    @Autowired
    private UserService userService;

    /**
     * 获取用户的车辆列表
     * 前端向后端发送令牌，后端从令牌中解析出用户ID
     * 查询车辆实例表中对应车主ID的车辆
     * 如果没有找到，返回状态码4004，表示用户未添加任何车辆
     * 如果找到，则返回4005，表示该用户有添加车辆
     * 并返回关联的车辆信息和车辆实例信息
     *
     * @param token 认证令牌
     * @param page 页码，默认为1
     * @param pageSize 每页数量，默认为10
     * @return 包含车辆信息的响应
     */
    @GetMapping
    public ResponseEntity<Map<String, Object>> getUserVehicles(
            @RequestHeader("Authorization") String token,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证令牌格式
            if (token == null || !token.startsWith("Bearer ")) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(400).body(response);
            }

            // 提取令牌内容
            String authToken = token.substring(7);

            // 从令牌中解析出用户ID (格式: token_u10000_fa6d66791fd64b1598aee56f925b23eb_PX0xDL7xgNi2xSMJ_1758076557259)
            String[] tokenParts = authToken.split("_");
            if (tokenParts.length < 5 || !tokenParts[1].startsWith("u")) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(400).body(response);
            }

            // 提取用户ID
            String userIdStr = tokenParts[1].substring(1); // 移除前缀 'u'
            Long userId;
            try {
                userId = Long.parseLong(userIdStr);
            } catch (NumberFormatException e) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "无效的用户ID格式");
                return ResponseEntity.status(400).body(response);
            }

            // 验证用户是否存在
            User user = userService.getUserByToken(authToken);
            if (user == null || !user.getId().equals(userId)) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "令牌无效或用户不存在");
                return ResponseEntity.status(401).body(response);
            }

            // 根据用户ID查询车辆实例
            List<VehicleInstance> vehicleInstances = vehicleInstanceService.getVehicleInstancesByOwnerId(userId);

            // 验证参数
            if (page < 1) {
                page = 1;
            }
            if (pageSize < 1) {
                pageSize = 10;
            } else if (pageSize > 10) {
                pageSize = 10; // 限制最多返回10条
            }

            // 检查是否有车辆实例
            if (vehicleInstances == null || vehicleInstances.isEmpty()) {
                response.put("status", "error");
                response.put("code", 4004);
                response.put("message", "用户未添加任何车辆");
                return ResponseEntity.status(400).body(response);
            }

            // 分页处理
            int startIndex = (page - 1) * pageSize;
            int endIndex = Math.min(startIndex + pageSize, vehicleInstances.size());
            List<VehicleInstance> pagedInstances = vehicleInstances.subList(startIndex, endIndex);

            // 构造包含车辆信息和车辆实例信息的响应数据
            List<Map<String, Object>> vehicleDataList = new ArrayList<>();
            for (VehicleInstance instance : pagedInstances) {
                Map<String, Object> vehicleData = new HashMap<>();
                
                // 添加车辆实例信息
                vehicleData.put("instanceId", instance.getId());
                vehicleData.put("licensePlate", instance.getLicensePlate());
                vehicleData.put("dailyRate", instance.getDailyRate());
                vehicleData.put("mileage", instance.getMileage());
                vehicleData.put("availableStart", instance.getAvailableStart());
                vehicleData.put("availableEnd", instance.getAvailableEnd());
                vehicleData.put("status", instance.getStatus());
                vehicleData.put("rentalCount", instance.getRentalCount());
                vehicleData.put("nextMaintenance", instance.getNextMaintenance());
                vehicleData.put("insuranceInfo", instance.getInsuranceInfo());
                
                // 获取并添加关联的车辆信息
                VehicleInfo vehicleInfo = instance.getVehicleInfo();
                if (vehicleInfo != null) {
                    vehicleData.put("id", vehicleInfo.getId());
                    vehicleData.put("brand", vehicleInfo.getBrand());
                    vehicleData.put("model", vehicleInfo.getModel());
                    vehicleData.put("color", vehicleInfo.getColor());
                    vehicleData.put("seatCount", vehicleInfo.getSeatCount());
                    // 添加非空检查，防止空指针异常
                    vehicleData.put("powerType", vehicleInfo.getPowerType() != null ? vehicleInfo.getPowerType() : null);
                }
                
                vehicleDataList.add(vehicleData);
            }

            // 构造成功响应
            response.put("status", "success");
            response.put("code", 4005);
            response.put("message", "该用户有添加车辆");
            response.put("data", vehicleDataList);
            response.put("total", vehicleInstances.size());
            response.put("page", page);
            response.put("pageSize", pageSize);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 处理异常情况
            response.put("status", "error");
            response.put("code", 5000);
            response.put("message", "获取用户车辆信息失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 局部更新用户的某个车辆实例信息（仅覆盖非空字段），要求实例属于该用户
     */
    @PatchMapping("/{instanceId}")
    public ResponseEntity<Map<String, Object>> patchUserVehicleInstance(
            @RequestHeader("Authorization") String token,
            @PathVariable Integer instanceId,
            @RequestBody VehicleInstance payload) {
        Map<String, Object> response = new HashMap<>();
        try {
            if (token == null || !token.startsWith("Bearer ")) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(400).body(response);
            }
            String authToken = token.substring(7);
            String[] tokenParts = authToken.split("_");
            if (tokenParts.length < 5 || !tokenParts[1].startsWith("u")) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(400).body(response);
            }
            String userIdStr = tokenParts[1].substring(1);
            Long userId = Long.parseLong(userIdStr);

            User user = userService.getUserByToken(authToken);
            if (user == null || !user.getId().equals(userId)) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "令牌无效或用户不存在");
                return ResponseEntity.status(401).body(response);
            }

            VehicleInstance existing = vehicleInstanceService.getVehicleInstanceById(instanceId);
            if (existing == null) {
                response.put("status", "error");
                response.put("code", 4006);
                response.put("message", "车辆实例不存在");
                return ResponseEntity.status(404).body(response);
            }
            if (existing.getOwner() == null || existing.getOwner().getId() == null || !existing.getOwner().getId().equals(userId)) {
                response.put("status", "error");
                response.put("code", 4007);
                response.put("message", "无权限修改该车辆实例");
                return ResponseEntity.status(403).body(response);
            }

            payload.setId(instanceId);
            VehicleInstance updated = vehicleInstanceService.updateVehicleInstance(payload);
            response.put("status", "success");
            response.put("code", 2000);
            response.put("data", updated);
            return ResponseEntity.ok(response);
        } catch (IllegalArgumentException ex) {
            response.put("status", "error");
            response.put("code", 4001);
            response.put("message", ex.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (Exception ex) {
            response.put("status", "error");
            response.put("code", 5001);
            response.put("message", "更新车辆实例失败: " + ex.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 删除用户的车辆实例
     * 前端发送车辆实例ID，后端在数据库中找到对应信息并删除
     * @param token 认证令牌
     * @param instanceId 车辆实例ID
     * @return 删除结果
     */
    @DeleteMapping("/{instanceId}")
    public ResponseEntity<Map<String, Object>> deleteUserVehicle(
            @RequestHeader("Authorization") String token,
            @PathVariable Integer instanceId) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 验证令牌格式
            if (token == null || !token.startsWith("Bearer ")) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(400).body(response);
            }

            // 提取令牌内容
            String authToken = token.substring(7);
            String[] tokenParts = authToken.split("_");
            if (tokenParts.length < 5 || !tokenParts[1].startsWith("u")) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "无效的令牌格式");
                return ResponseEntity.status(400).body(response);
            }

            // 提取用户ID
            String userIdStr = tokenParts[1].substring(1);
            Long userId = Long.parseLong(userIdStr);

            // 验证用户是否存在
            User user = userService.getUserByToken(authToken);
            if (user == null || !user.getId().equals(userId)) {
                response.put("status", "error");
                response.put("code", 4000);
                response.put("message", "令牌无效或用户不存在");
                return ResponseEntity.status(401).body(response);
            }

            // 检查车辆实例是否存在
            VehicleInstance existing = vehicleInstanceService.getVehicleInstanceById(instanceId);
            if (existing == null) {
                response.put("status", "error");
                response.put("code", 4006);
                response.put("message", "车辆实例不存在");
                return ResponseEntity.status(404).body(response);
            }

            // 检查车辆实例是否属于当前用户
            if (existing.getOwner() == null || existing.getOwner().getId() == null || !existing.getOwner().getId().equals(userId)) {
                response.put("status", "error");
                response.put("code", 4007);
                response.put("message", "无权限删除该车辆实例");
                return ResponseEntity.status(403).body(response);
            }

            // 删除车辆实例
            vehicleInstanceService.deleteVehicleInstance(instanceId);

            // 构造成功响应
            response.put("status", "success");
            response.put("code", 2000);
            response.put("message", "车辆实例删除成功");
            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException ex) {
            response.put("status", "error");
            response.put("code", 4001);
            response.put("message", ex.getMessage());
            return ResponseEntity.badRequest().body(response);
        } catch (Exception ex) {
            response.put("status", "error");
            response.put("code", 5001);
            response.put("message", "删除车辆实例失败: " + ex.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }
}